package org.chen.hotel.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.chen.common.hotel.request.HotelSearchRequest;
import org.chen.common.hotel.Hotel;
import org.chen.hotel.mapper.HotelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
@Slf4j
public class DataService {

    @Autowired
    private HotelMapper hotelMapper;

    public void saveHotelsToDatabase(JsonNode jsonNode, HotelSearchRequest request) {
        try {
            JsonNode hotelListNode = jsonNode.path("data").path("hotelList");
            if (hotelListNode.isArray()) {
                for (JsonNode hotelNode : hotelListNode) {
                    Hotel hotel = convertToHotelEntity(hotelNode, request);
                    if (hotel != null) {
                        // 检查是否已存在，避免重复插入
                        QueryWrapper<Hotel> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("hotel_name", hotel.getHotelName())
                                .eq("check_in_date", hotel.getCheckInDate())
                                .eq("check_out_date", hotel.getCheckOutDate());

                        Hotel existingHotel = hotelMapper.selectOne(queryWrapper);
                        if (existingHotel == null) {
                            hotelMapper.insert(hotel);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    private Hotel convertToHotelEntity(JsonNode hotelNode, HotelSearchRequest request) {
        try {
            Hotel hotel = new Hotel();

            JsonNode hotelInfo = hotelNode.path("hotelInfo");
            JsonNode nameInfo = hotelInfo.path("nameInfo");
            JsonNode positionInfo = hotelInfo.path("positionInfo");
            JsonNode commentInfo = hotelInfo.path("commentInfo");
            JsonNode hotelStar = hotelInfo.path("hotelStar");
            JsonNode hotelImages = hotelInfo.path("hotelImages");

            // 酒店基本信息
            hotel.setHotelName(nameInfo.path("name").asText());
            hotel.setHotelNameEn(nameInfo.path("enName").asText());
            hotel.setHotelStar(hotelStar.path("star").asInt());
            hotel.setAddress(positionInfo.path("address").asText());
            hotel.setPositionDesc(positionInfo.path("positionDesc").asText());
            hotel.setCityName(positionInfo.path("cityName").asText());

            // 坐标信息
            JsonNode coordinates = positionInfo.path("mapCoordinate");
            if (coordinates.isArray() && coordinates.size() > 0) {
                JsonNode coord = coordinates.get(0);
                hotel.setLatitude(new BigDecimal(coord.path("latitude").asText()));
                hotel.setLongitude(new BigDecimal(coord.path("longitude").asText()));
            }

            // 评分信息
            hotel.setCommentScore(commentInfo.path("commentScore").asText());
            hotel.setCommenterNumber(commentInfo.path("commenterNumber").asText());

            // 房间和价格信息
            JsonNode roomInfo = hotelNode.path("roomInfo");
            if (roomInfo.isArray() && roomInfo.size() > 0) {
                JsonNode firstRoom = roomInfo.get(0);
                hotel.setRoomName(firstRoom.path("summary").path("saleRoomName").asText());

                JsonNode bedInfo = firstRoom.path("bedInfo");
                if (bedInfo.path("contentList").isArray() && bedInfo.path("contentList").size() > 0) {
                    hotel.setBedInfo(bedInfo.path("contentList").get(0).asText());
                }

                JsonNode priceInfo = firstRoom.path("priceInfo");
                hotel.setPrice(new BigDecimal(priceInfo.path("price").asInt()));
                hotel.setPriceUnit("¥");
                hotel.setPriceExplanation(priceInfo.path("priceExplanation").asText());
                if (priceInfo.has("deletePrice")) {
                    hotel.setDeletePrice(new BigDecimal(priceInfo.path("deletePrice").asInt()));
                }
            }

            // 图片信息
            JsonNode multiImgs = hotelImages.path("multiImgs");
            if (multiImgs.isArray() && multiImgs.size() > 0) {
                hotel.setImageUrl(multiImgs.get(0).path("url").asText());
            }

            // 搜索条件
            hotel.setSearchKeywords(request.getKeyword());
            hotel.setCheckInDate(request.getCheckInDate());
            hotel.setCheckOutDate(request.getCheckOutDate());
            hotel.setRoomQuantity(request.getRoomQuantity());
            hotel.setAdultCount(request.getAdultCount());
            hotel.setChildCount(request.getChildCount());

            // 时间戳
            hotel.setCreateTime(LocalDateTime.now());
            hotel.setUpdateTime(LocalDateTime.now());

            return hotel;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
